#!/usr/bin/env python3
"""
持久化部署脚本
支持Windows服务、Linux systemd服务等方式
"""

import os
import sys
import platform
import subprocess
import shutil
from pathlib import Path

def create_windows_service():
    """创建Windows服务配置"""
    service_script = """
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import sys
import os
from pathlib import Path

# 添加项目路径到Python路径
project_path = Path(__file__).parent
sys.path.insert(0, str(project_path))

from app import create_app

class ImageGenAPIService(win32serviceutil.ServiceFramework):
    _svc_name_ = "ImageGenAPI"
    _svc_display_name_ = "图生图转接API服务"
    _svc_description_ = "基于Gemini 2.0 Flash的图片生成和编辑API服务"

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        socket.setdefaulttimeout(60)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                            servicemanager.PYS_SERVICE_STARTED,
                            (self._svc_name_, ''))
        self.main()

    def main(self):
        try:
            # 切换到项目目录
            os.chdir(str(project_path))
            
            # 创建Flask应用
            app = create_app()
            
            # 启动服务
            app.run(host='0.0.0.0', port=5000, debug=False)
            
        except Exception as e:
            servicemanager.LogErrorMsg(f"服务启动失败: {e}")

if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(ImageGenAPIService)
"""
    
    with open('windows_service.py', 'w', encoding='utf-8') as f:
        f.write(service_script)
    
    print("✅ Windows服务脚本已创建: windows_service.py")
    print("安装服务命令: python windows_service.py install")
    print("启动服务命令: python windows_service.py start")
    print("停止服务命令: python windows_service.py stop")
    print("卸载服务命令: python windows_service.py remove")

def create_systemd_service():
    """创建Linux systemd服务配置"""
    current_dir = os.getcwd()
    python_path = sys.executable
    
    service_content = f"""[Unit]
Description=图生图转接API服务
After=network.target

[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory={current_dir}
Environment=PATH={os.path.dirname(python_path)}
ExecStart={python_path} -m gunicorn -w 4 -b 0.0.0.0:5000 --timeout 120 app:create_app()
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
"""
    
    service_file = 'image-gen-api.service'
    with open(service_file, 'w', encoding='utf-8') as f:
        f.write(service_content)
    
    print(f"✅ Systemd服务文件已创建: {service_file}")
    print("安装步骤:")
    print(f"1. sudo cp {service_file} /etc/systemd/system/")
    print("2. sudo systemctl daemon-reload")
    print("3. sudo systemctl enable image-gen-api")
    print("4. sudo systemctl start image-gen-api")
    print("5. sudo systemctl status image-gen-api")

def create_nginx_config():
    """创建Nginx反向代理配置"""
    nginx_config = """server {
    listen 80;
    server_name your-domain.com;  # 替换为您的域名

    # 限制请求大小
    client_max_body_size 20M;

    # API代理
    location / {
        proxy_pass http://127.0.0.1:5000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        
        # 超时设置
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }

    # 静态文件
    location /static/ {
        alias /path/to/your/static/files/;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    # 日志
    access_log /var/log/nginx/image-gen-api.access.log;
    error_log /var/log/nginx/image-gen-api.error.log;
}

# HTTPS配置 (可选)
server {
    listen 443 ssl;
    server_name your-domain.com;

    ssl_certificate /path/to/your/certificate.crt;
    ssl_certificate_key /path/to/your/private.key;

    client_max_body_size 20M;

    location / {
        proxy_pass http://127.0.0.1:5000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }

    access_log /var/log/nginx/image-gen-api-ssl.access.log;
    error_log /var/log/nginx/image-gen-api-ssl.error.log;
}
"""
    
    with open('nginx.conf', 'w', encoding='utf-8') as f:
        f.write(nginx_config)
    
    print("✅ Nginx配置文件已创建: nginx.conf")
    print("配置步骤:")
    print("1. 编辑nginx.conf，替换域名和路径")
    print("2. sudo cp nginx.conf /etc/nginx/sites-available/image-gen-api")
    print("3. sudo ln -s /etc/nginx/sites-available/image-gen-api /etc/nginx/sites-enabled/")
    print("4. sudo nginx -t")
    print("5. sudo systemctl reload nginx")

def create_supervisor_config():
    """创建Supervisor配置"""
    current_dir = os.getcwd()
    python_path = sys.executable
    
    supervisor_config = f"""[program:image-gen-api]
command={python_path} -m gunicorn -w 4 -b 127.0.0.1:5000 --timeout 120 app:create_app()
directory={current_dir}
user=www-data
autostart=true
autorestart=true
redirect_stderr=true
stdout_logfile=/var/log/supervisor/image-gen-api.log
stdout_logfile_maxbytes=10MB
stdout_logfile_backups=5
environment=PATH="{os.path.dirname(python_path)}"
"""
    
    with open('supervisor.conf', 'w', encoding='utf-8') as f:
        f.write(supervisor_config)
    
    print("✅ Supervisor配置文件已创建: supervisor.conf")
    print("配置步骤:")
    print("1. sudo cp supervisor.conf /etc/supervisor/conf.d/image-gen-api.conf")
    print("2. sudo supervisorctl reread")
    print("3. sudo supervisorctl update")
    print("4. sudo supervisorctl start image-gen-api")
    print("5. sudo supervisorctl status image-gen-api")

def create_pm2_config():
    """创建PM2配置"""
    pm2_config = {
        "name": "image-gen-api",
        "script": "run.py",
        "interpreter": "python3",
        "instances": 1,
        "exec_mode": "fork",
        "watch": False,
        "max_memory_restart": "500M",
        "env": {
            "FLASK_ENV": "production"
        },
        "log_file": "./logs/app.log",
        "out_file": "./logs/out.log",
        "error_file": "./logs/error.log",
        "log_date_format": "YYYY-MM-DD HH:mm:ss Z"
    }
    
    import json
    with open('ecosystem.config.json', 'w', encoding='utf-8') as f:
        json.dump(pm2_config, f, indent=2, ensure_ascii=False)
    
    # 创建日志目录
    os.makedirs('logs', exist_ok=True)
    
    print("✅ PM2配置文件已创建: ecosystem.config.json")
    print("使用步骤:")
    print("1. npm install -g pm2")
    print("2. pm2 start ecosystem.config.json")
    print("3. pm2 save")
    print("4. pm2 startup")

def create_production_run_script():
    """创建生产环境运行脚本"""
    if platform.system() == "Windows":
        script_content = """@echo off
echo 启动生产环境服务...

REM 检查.env文件
if not exist .env (
    echo 错误: .env文件不存在，请先配置环境变量
    pause
    exit /b 1
)

REM 创建日志目录
if not exist logs mkdir logs

REM 启动服务
echo 启动图生图转接API服务 (生产模式)...
python -m gunicorn -w 4 -b 0.0.0.0:5000 --timeout 120 --access-logfile logs/access.log --error-logfile logs/error.log app:create_app()

pause
"""
        with open('start_production.bat', 'w', encoding='utf-8') as f:
            f.write(script_content)
        print("✅ Windows生产环境脚本已创建: start_production.bat")
    
    else:
        script_content = """#!/bin/bash

echo "启动生产环境服务..."

# 检查.env文件
if [ ! -f .env ]; then
    echo "错误: .env文件不存在，请先配置环境变量"
    exit 1
fi

# 创建日志目录
mkdir -p logs

# 启动服务
echo "启动图生图转接API服务 (生产模式)..."
python3 -m gunicorn -w 4 -b 0.0.0.0:5000 --timeout 120 \\
    --access-logfile logs/access.log \\
    --error-logfile logs/error.log \\
    --pid logs/gunicorn.pid \\
    --daemon \\
    app:create_app()

echo "服务已在后台启动"
echo "PID文件: logs/gunicorn.pid"
echo "访问日志: logs/access.log"
echo "错误日志: logs/error.log"
echo ""
echo "停止服务: kill \$(cat logs/gunicorn.pid)"
"""
        with open('start_production.sh', 'w', encoding='utf-8') as f:
            f.write(script_content)
        os.chmod('start_production.sh', 0o755)
        print("✅ Linux生产环境脚本已创建: start_production.sh")

def main():
    """主函数"""
    print("🚀 图生图API持久化部署配置生成器")
    print("=" * 50)
    
    system = platform.system()
    print(f"检测到系统: {system}")
    print()
    
    # 创建生产环境运行脚本
    create_production_run_script()
    print()
    
    if system == "Windows":
        print("Windows部署选项:")
        print("1. Windows服务 (推荐)")
        create_windows_service()
        print()
        
        print("2. PM2 (需要Node.js)")
        create_pm2_config()
        print()
    
    elif system == "Linux":
        print("Linux部署选项:")
        print("1. Systemd服务 (推荐)")
        create_systemd_service()
        print()
        
        print("2. Supervisor")
        create_supervisor_config()
        print()
        
        print("3. PM2 (需要Node.js)")
        create_pm2_config()
        print()
        
        print("4. Nginx反向代理配置")
        create_nginx_config()
        print()
    
    print("📋 部署建议:")
    print("1. 生产环境建议使用Gunicorn + Nginx")
    print("2. 确保.env文件中的配置适合生产环境")
    print("3. 定期备份日志文件")
    print("4. 监控服务状态和资源使用")
    print("5. 设置防火墙规则")

if __name__ == "__main__":
    main()
